package com.xxx.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xxx.dto.ResponseDTO;
import com.xxx.util.CommonUtil;

/**
 * 文件上传Controller
 */
@Controller
public class UploadController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	private static String CREDENTPIC_PATH = "/opt/credentpic/"; // 认证图片存放路径
	
	/**
     * 上传图片页面初始化
     */
    @RequestMapping("/testUploadPic")
    public ModelAndView testUploadPic(){
    	logger.info("enter method testUploadPic().");
        ModelAndView mav = new ModelAndView("uploadPic");
        return mav;
    }

	/**
	 * 10. 上传图片接口 uploadPic
	 */
	@RequestMapping(value="/uploadPic", method=RequestMethod.POST)
	@ResponseBody
	public ResponseDTO uploadPic(HttpServletRequest request, HttpServletResponse response,
			MultipartFile file) throws IllegalStateException, IOException {
    	logger.info("enter method uploadPic().");
		if (file != null) {	// 判断上传的文件是否为空
			String fileName = file.getOriginalFilename();	// 文件原名称
			if(StringUtils.isEmpty(fileName)) { // 文件名为空
				logger.error("uploadPic | 文件名称为空");
				return ResponseDTO.builtFail("file name is empty.");
			}
			logger.info("uploadPic | 上传的文件原名称:" + fileName);
			
			if(fileName.indexOf(".") == -1) { // 文件类型不存在
				logger.error("file type is empty");
				return ResponseDTO.builtFail("file type is empty.");
			}
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (!StringUtils.isEmpty(fileType)) {	// 判断文件类型是否为空
				if ("JPG".equals(fileType.toUpperCase()) 
					|| "JPEG".equals(fileType.toUpperCase()) 
					|| "PNG".equals(fileType.toUpperCase())) {
					// 设置存放图片文件的路径
					String path = CREDENTPIC_PATH; //PropertyUtil.getCtxProperty("credentpic");
					logger.info("uploadPic | 存放图片文件的路径:" + path);
//					// 如果路径不存在，则先创建文件夹 // 文件夹肯定存在
//					File dirFile = new File(path);
//					if(!dirFile.exists()) {
//						dirFile.mkdir();
//						logger.info("uploadPic | path not exists, create path success.");
//					}
					// 重命名文件名称，防止被遍历
					String newFileName = CommonUtil.getUUID() + "." + fileType;
					logger.info("uploadPic | 图片新文件名:" + newFileName);
					String filePath = path + newFileName;
					// 转存文件到指定的路径
					file.transferTo(new File(filePath));
					logger.info("uploadPic | 文件成功上传到指定目录下");
					
					return ResponseDTO.builtSuccess(newFileName);
				} else {
					logger.error("uploadPic | 文件类型不是JPG或PNG.");
					return ResponseDTO.builtFail("file type is not jpg or png.");
				}
			} else {
				logger.error("uploadPic | 文件类型为空");
				return ResponseDTO.builtFail("file type is empty.");
			}
		} else {
			logger.error("uploadPic | 没有找到相对应的文件");
			return ResponseDTO.builtFail("file is not exists");
		}
	}

}
